package com.iwhalecloud.citybrain.flow.platform.manager.application.common.command;

import java.io.Serializable;
import java.util.Map;
import java.util.Objects;

import com.iwhalecloud.citybrain.flow.platform.manager.application.service.FlowModelVariableService;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.SpringUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.common.client.HttpStartProcessInstanceDto;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.common.impl.interceptor.Command;
import org.flowable.engine.common.impl.interceptor.CommandContext;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.ProcessInstanceHelper;
import org.flowable.engine.runtime.ProcessInstance;

/**
 * @author lilh
 * @date 2019-02-12 16:31
 */
public class StartProcessInstanceCmd implements Command<ProcessInstance>, Serializable {
    private static final long serialVersionUID = -869400077747557483L;

    private HttpStartProcessInstanceDto startProcessInstanceDto;

    public StartProcessInstanceCmd(HttpStartProcessInstanceDto startProcessInstanceDto) {
        this.startProcessInstanceDto = startProcessInstanceDto;
    }

    @Override
    public ProcessInstance execute(CommandContext commandContext) {
        RuntimeService runtimeService = CommandContextUtil.getProcessEngineConfiguration(commandContext).getRuntimeService();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(startProcessInstanceDto.getProcessInstanceId()).active().singleResult();
        if (Objects.nonNull(processInstance)) {
            Map<String,Object> variables = startProcessInstanceDto.getFlowParamObjectMap();
            //初始化流程模板里的默认值
            variables = initModelVariablesDefaultValue(processInstance.getDeploymentId(),variables);
            setProcessInstanceVariable(processInstance, variables);
            ProcessInstanceHelper processInstanceHelper = CommandContextUtil.getProcessEngineConfiguration(commandContext).getProcessInstanceHelper();
            processInstanceHelper.startProcessInstance((ExecutionEntity) processInstance, commandContext, variables);
        }
        return processInstance;
    }

    private Map<String,Object> initModelVariablesDefaultValue(String deploymentId,Map<String,Object> variables) {
        FlowModelVariableService flowModelVariableService = SpringUtils.getBean(FlowModelVariableService.class);
        return flowModelVariableService.setDefaultValueToVariables(deploymentId,variables);
    }

    private void setProcessInstanceVariable(ProcessInstance processInstance, Map<String, Object> variables) {
        if (variables != null) {
            ((ExecutionEntity) processInstance).setVariables(variables);
        }
    }
}
